/*
 *
 *  * Copyright (c) 2016. For Intelligent Group.
 *
 */

package com.intelligent.ispc.client.core.view.analysis;

import com.google.common.collect.Lists;
import com.intelligent.ispc.client.core.controller.SpcController;
import com.intelligent.ispc.client.core.modal.SearchItemTableModel;
import com.intelligent.ispc.client.event.SearchItemDoubleClickEvent;
import com.intelligent.ispc.client.event.SearchItemOneClickEvent;
import com.intelligent.ispc.client.event.SearchParamsChangeEvent;
import com.intelligent.ispc.client.ex.JTextFieldEx;
import com.intelligent.ispc.client.utils.ApplicationBeanUtils;
import com.intelligent.ispc.client.utils.EventBusUtils;
import com.intelligent.ispc.client.utils.GBC;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

/**
 * Created by Peter on 2016/9/2.
 */
public class AnalysisItemPanel extends JPanel {
    private SearchItemTableModel testItemModel;
    private SpcController spcController;
    private String[] testItemColumn;
    private String moduleKey;

    private String cacheData;

    /**
     * Constructor
     *
     * @param module which panel
     */
    public AnalysisItemPanel(String module) {
        this.moduleKey = module;
        initComponents();
    }

    /**
     * Initialize component
     */
    public void initComponents() {
        final int textFieldSize = 15;
        testItemFilter = new JTextFieldEx(textFieldSize);
        testItemTable = new JTable();

        //init Item Panel
        JScrollPane testItemScroll = new JScrollPane();
        testItemScroll.setViewportView(testItemTable);
        final Dimension testItemScrollSize = new Dimension(0, 100);
        testItemScroll.setPreferredSize(testItemScrollSize);

        this.setLayout(new GridBagLayout());
        this.setBorder(BorderFactory.createTitledBorder("Test Items"));
        this.add(testItemScroll, new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));
        this.add(testItemFilter, new GBC(0, 1).setFill(GBC.HORIZONTAL).setWeight(100, 0));
        initDatamodal();
        initView();
        initComponentsListener();
    }

    /**
     * Initialize dataModul
     */
    public void initDatamodal() {
        testItemColumn = new String[]{"Name"};
        testItemModel = new SearchItemTableModel(testItemColumn);
        testItemTable.setModel(testItemModel);
    }

    /**
     * Initialize view
     */
    public void initView() {
        testItemSorter = new TableRowSorter(testItemModel);
        testItemTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        testItemTable.setRowSorter(testItemSorter);
        testItemTable.getTableHeader().setVisible(false);
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setPreferredSize(new Dimension(0, 0));
        testItemTable.getTableHeader().setDefaultRenderer(renderer);
        testItemTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
        testItemFilter.setPlaceHolder("Filter");
    }

    /**
     * Initialize component listener
     */
    public void initComponentsListener() {
        testItemFilter.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                update(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                update(e);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                update(e);
            }

            private void update(DocumentEvent e) {
                String value = testItemFilter.getText();
                if (value.length() == 0) {
                    testItemSorter.setRowFilter(null);
                } else {
                    testItemSorter.setRowFilter(RowFilter.regexFilter(value, 0));
                }
            }
        });
        testItemTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1) {
                    testItemModel.setSelectedName((String) testItemModel.getValueAt(testItemTable.getSelectedRow(), 0));
                    EventBusUtils.post(new SearchItemOneClickEvent(moduleKey));
                    EventBusUtils.post(new SearchParamsChangeEvent(moduleKey, SearchParamsChangeEvent.TYPE_ITEM, testItemModel.isValidCatchData()));
                } else if (e.getClickCount() == 2) {
                    testItemModel.setCacheName((String) testItemModel.getValueAt(testItemTable.getSelectedRow(), 0));
                    EventBusUtils.post(new SearchItemDoubleClickEvent(moduleKey));
                }
            }
        });
    }

    /**
     * Call when change the CSV file and analysis
     *
     * @param files file names
     */
    public void onFileChange(java.util.List<String> files) {
        if (files == null || files.isEmpty()) {
            onReceivedTestItems(new ArrayList<>());
        } else {
            testItemModel.setData(Lists.newArrayList());
            getSpcController().findTestItemNames(files);
        }
    }

    /**
     * Call when change the testItem and search it
     *
     * @param testItemNames testItem names list
     */
    public void onReceivedTestItems(java.util.List<String> testItemNames) {
        testItemModel.setData(testItemNames);
        testItemFilter.setText("");
    }

    /**
     * Get the selected name
     *
     * @return a line
     */
    public String getSelectedName() {
        if (testItemTable.getSelectedRow() == -1) {
            return null;
        }
        int row = testItemTable.convertRowIndexToModel(testItemTable.getSelectedRow());
        return (String) testItemModel.getValueAt(row, 0);
    }

    public SearchItemTableModel getTestItemModel() {
        return testItemModel;
    }

    public java.util.List<String> getItemNames() {
        return testItemModel.getData();
    }

    /**
     * Set cache data
     *
     * @param cacheName cacheName
     */
    public void setCacheData(String cacheName) {
        testItemModel.setCacheName(cacheName);
    }

    public String getCacheData() {
        return testItemModel.getCacheName();
    }

    /**
     * Clean panel
     */
    public void cleanPanel() {
        testItemTable.removeAll();
    }

    private SpcController getSpcController() {
        if (spcController == null) {
            spcController = ApplicationBeanUtils.getBean(SpcController.class);
        }
        return spcController;
    }

    private JTextFieldEx testItemFilter;
    private TableRowSorter testItemSorter;
    private JTable testItemTable;
}
